﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.SessionState;
using SAS.Bussiness;
using SAS.Core.Entity;
using SAS.Core.Result;

namespace SAS.WebSite.Service
{
    /// <summary>
    /// Summary description for WorkspaceSubmitHandler
    /// </summary>
    public class WorkspaceSubmitHandler : IHttpHandler, IRequiresSessionState //IRequiresSessionState --> to access Session.
    {
        public void ProcessRequest(HttpContext context)
        {
            WorkspaceDetail workspaceDetail = new WorkspaceDetail();
            string jsonReturn = String.Empty;

            if (context.Request.Form.Count != 0)
            {
                string activateCloneSaveInfo = Convert.ToString(context.Request.Form["activateCloneSaveInfo"]);

                //Detect submit type
                string submitType = Convert.ToString(context.Request.Form["formSubmitType"]);

                string evironment = Convert.ToString(context.Request.Form["environment"]);

                //Detect workspaceId
                workspaceDetail.Workspace.pkWorkSpace_ID = Convert.ToString(context.Request.Form["wspIdId"]);

                //Workspace detail
                workspaceDetail.Workspace.WorkSpaceName = Convert.ToString(context.Request.Form["txtWorkSpaceName"]);
                workspaceDetail.Workspace.WorkSpaceNote = Convert.ToString(context.Request.Form["txtWorkSpaceNote"]);
                
                //Client Administration Group
                workspaceDetail.Client.ClientName = Convert.ToString(context.Request.Form["txtClientName"]);
                workspaceDetail.Client.StrClientId = Convert.ToString(context.Request.Form["txtClientId"]);
                workspaceDetail.Client.pkClient_ID = Convert.ToString(context.Request.Form["pkClientId"]);

                //Detect file uploaded.
                if (context.Request.Files.Count > 0 && context.Request.Files["clientFileUpload"] != null)
                {
                    workspaceDetail.Client.LogoFileName = Path.GetFileName(context.Request.Files["clientFileUpload"].FileName);
                    workspaceDetail.Client.LogoFileStream = context.Request.Files["clientFileUpload"].InputStream;
                    workspaceDetail.Client.LogoFileStreamSize = context.Request.Files["clientFileUpload"].ContentLength;
                }

                //Client Information
                workspaceDetail.Client.ContactName = Convert.ToString(context.Request.Form["txtClientContactName"]);
                workspaceDetail.Client.Email = Convert.ToString(context.Request.Form["txtClientEmail"]);
                workspaceDetail.Client.WebSite = Convert.ToString(context.Request.Form["txtClientWebsite"]);
                workspaceDetail.Client.Address1 = Convert.ToString(context.Request.Form["txtClientAddress1"]);
                workspaceDetail.Client.Address2 = Convert.ToString(context.Request.Form["txtClientAddress2"]);
                workspaceDetail.Client.Phone1 = Convert.ToString(context.Request.Form["txtClientTelephone1"]);
                workspaceDetail.Client.Phone2 = Convert.ToString(context.Request.Form["txtClientTelephone2"]);
                workspaceDetail.Client.Fax = Convert.ToString(context.Request.Form["txtClientFax"]);
                workspaceDetail.Client.City = Convert.ToString(context.Request.Form["txtClientCity"]);
                workspaceDetail.Client.StateProv = Convert.ToString(context.Request.Form["txtClientStateProv"]);
                workspaceDetail.Client.PostalCode = Convert.ToString(context.Request.Form["txtClientPostalCode"]);
                workspaceDetail.Client.Country = Convert.ToString(context.Request.Form["txtClientCountry"]);

                //Accepted Payments
                workspaceDetail.Client.StrWebPayment = Convert.ToString(context.Request.Form["chkClientWebPayment"]);
                workspaceDetail.Client.StrACHPayment = Convert.ToString(context.Request.Form["chkClientACHPayment"]);
                workspaceDetail.Client.StrDebitPayment = Convert.ToString(context.Request.Form["chkClientDebitPayment"]);
                workspaceDetail.Client.StrCreditPayment = Convert.ToString(context.Request.Form["chkClientCreditCardPayment"]);
                workspaceDetail.Client.StrVISA = Convert.ToString(context.Request.Form["chkClientVisaCardPayment"]);
                workspaceDetail.Client.StrMastercard = Convert.ToString(context.Request.Form["chkClientMasterCardPayment"]);
                workspaceDetail.Client.StrAMEX = Convert.ToString(context.Request.Form["chkClientAmericanExpressCardPayment"]);
                workspaceDetail.Client.StrDiscover = Convert.ToString(context.Request.Form["chkClientDiscoverNetworkCardPayment"]);
                
                //Connection Information
                workspaceDetail.ClientIOFile.ClientShortName = Convert.ToString(context.Request.Form["txtClientShortName"]);
                workspaceDetail.ClientIOFile.StriataServerDesc = Convert.ToString(context.Request.Form["txtStriataDescription"]);
                workspaceDetail.ClientIOFile.StriataServerNameOrIP = Convert.ToString(context.Request.Form["txtStriataAddress"]);
                workspaceDetail.ClientIOFile.StriataUsername = Convert.ToString(context.Request.Form["txtStriataUsername"]);
                workspaceDetail.ClientIOFile.StriataUserPW = Convert.ToString(context.Request.Form["txtStriataPassword"]);
                workspaceDetail.ClientIOFile.FedPayServerDesc = Convert.ToString(context.Request.Form["txtFedPayDescription"]);
                workspaceDetail.ClientIOFile.FedPayServerNameOrIP = Convert.ToString(context.Request.Form["txtFedPayAddress"]);
                workspaceDetail.ClientIOFile.FedPayUsername = Convert.ToString(context.Request.Form["txtFedPayUsername"]);
                workspaceDetail.ClientIOFile.FedPayUserPW = Convert.ToString(context.Request.Form["txtFedPayPassword"]);

                //System Preferences
                workspaceDetail.Client.StrSubscribeRptUpdate = Convert.ToString(context.Request.Form["radioAutoOptin"]);
                workspaceDetail.Client.StrUnsubscribeRptUpdate = Convert.ToString(context.Request.Form["radioAutoOptout"]);
                workspaceDetail.Client.StrPMOverrideCustomer = Convert.ToString(context.Request.Form["radioPrintmachadd"]);
                workspaceDetail.Client.StrPMAllowIntro = Convert.ToString(context.Request.Form["radioPrintachOptin"]);
                workspaceDetail.Client.StrCustomerStatusTimeOut = Convert.ToString(context.Request.Form["radioOptindays"]);
                workspaceDetail.Client.StrClientDefaultInfo = Convert.ToString(context.Request.Form["radioDefaultpm"]);
                workspaceDetail.Client.StrUseClientPaymentMethod = Convert.ToString(context.Request.Form["radioAccpayset"]);

                //Get current user logged in to system from session.
                var user = HttpContext.Current.Session["User"] as User;

                //Call to business layer
                WorkspaceBO workspaceBo = new WorkspaceBO
                    {
                        FromIP = ClientIp
                    };

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                //get the physical web path.
                string webPhysicalPath = Path.GetDirectoryName(HttpContext.Current.Request.MapPath(""));

                //get default logo path.
                string defaultLogo = ConfigurationManager.AppSettings.Get("DefaultLogo");

                //locate default logo.
                string defaultLogoPath = String.Format(@"{0}\{1}", webPhysicalPath, defaultLogo);

                switch (submitType)
                {
                    case "save": //For SAVE case, the data returned is just submitType and error message(if it's exist).
                        SASResult<string> updateResult = workspaceBo.UpdateWorkspace(user, workspaceDetail, defaultLogoPath);
                        var updateJsonObject = new
                        {
                            submitType,
                            errorMessage = String.IsNullOrEmpty(updateResult.Message) ? String.Empty : updateResult.Message
                        };
                        //get the json result
                        jsonReturn = serializer.Serialize(updateJsonObject);

                        break;
                    case "addNew": //For ADDNEW case, the data returned is just submitType and error message(if it's exist).
                        SASResult<string> addNewResult = workspaceBo.AddNewWorkspace(user, workspaceDetail, defaultLogoPath);
                        var addNewJsonObject = new
                            {
                                submitType,
                                errorMessage = String.IsNullOrEmpty(addNewResult.Message) ? String.Empty : addNewResult.Message
                            };

                            //get the json result
                        jsonReturn = serializer.Serialize(addNewJsonObject);
                     
                        break;

                    case "active":   //For ACTIVE case, the data returned also contain admin username and password for sending email purpose.

                        SASResult<string> activeResult = workspaceBo.Activate(user, workspaceDetail, evironment, defaultLogoPath);

                        if (activeResult.IsSucessful)
                        {
                            var activeJsonObject = new
                                {
                                    submitType,
                                    AdminUserName = activeResult.OutputResult.ContainsKey("AdminUsername") ? activeResult.OutputResult["AdminUsername"] : String.Empty, //admin username
                                    AdminPassword = activeResult.OutputResult.ContainsKey("AdminPassword") ? activeResult.OutputResult["AdminPassword"] : String.Empty, // admin password
                                    ClientName = activeResult.OutputResult.ContainsKey("ClientName") ? activeResult.OutputResult["ClientName"] : String.Empty, // Client name
                                    ClientID = activeResult.OutputResult.ContainsKey("ClientId") ? activeResult.OutputResult["ClientId"] : String.Empty, // Client Id
                                    WorkspaceName = activeResult.OutputResult.ContainsKey("WorkspaceName") ? activeResult.OutputResult["WorkspaceName"] : String.Empty, // WorkspaceName
                                    ActivedBy = activeResult.OutputResult.ContainsKey("ActivedBy") ? activeResult.OutputResult["ActivedBy"] : String.Empty, // ActivedBy
                                    SourceEnv = activeResult.OutputResult.ContainsKey("SourceEnv") ? activeResult.OutputResult["SourceEnv"] : String.Empty, // Source environment
                                    TargetEnv = activeResult.OutputResult.ContainsKey("TargetEnv") ? activeResult.OutputResult["TargetEnv"] : String.Empty, // Target environment
                                    ActivedOn = activeResult.OutputResult.ContainsKey("ActivedOn") ? activeResult.OutputResult["ActivedOn"] : String.Empty, // ActivedOn
                                    Url = activeResult.OutputResult.ContainsKey("ActivedOn") ? activeResult.OutputResult["url"] : String.Empty, // DPM access url
                                    ToEmailAdress = String.Empty,
                                    errorMessage = String.IsNullOrEmpty(activeResult.Message) ? String.Empty : activeResult.Message
                                };
                            jsonReturn = serializer.Serialize(activeJsonObject);
                        }
                        else
                        {
                            var activeJsonObject = new
                            {
                                submitType,
                                errorMessage = activeResult.Message
                            };
                            jsonReturn = serializer.Serialize(activeJsonObject);
                        }
                        break;

                    case "activeCloneSave":
                        //string strjson = serializer.Serialize(activateCloneSaveInfo);
                        ActiavateCloneSaveWorkspace actiavateCloneSaveWorkspace = serializer.Deserialize<ActiavateCloneSaveWorkspace>(activateCloneSaveInfo);
                        SASResult<string> activeCloneSaveResult = workspaceBo.ActivateCloneSavedWorkspace(user, workspaceDetail, actiavateCloneSaveWorkspace, defaultLogoPath);
                        var activeCloneSaveObject = new
                            {
                                submitType,
                                errorMessage = String.IsNullOrEmpty(activeCloneSaveResult.Message) ? String.Empty : activeCloneSaveResult.Message
                            };

                            //get the json result
                        jsonReturn = serializer.Serialize(activeCloneSaveObject);
                        break;
                }
                
            }

            context.Response.Write(jsonReturn);
        }

        private string ClientIp
        {
            get
            {
                HttpRequest currentRequest = HttpContext.Current.Request;
                string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipAddress == null || ipAddress.ToLower() == "unknown")
                    ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

                return ipAddress;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}